package com.wdhcr.controller;

import com.wdhcr.entity.Comment;
import com.wdhcr.enums.ResultCode;
import com.wdhcr.service.CommentService;
import com.wdhcr.utils.JwtUtil;
import com.wdhcr.utils.ResponseResult;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
/*
 * @description: 评论信息控制器
 * @author: wdhcr
 * @dateTime: 2020/4/12 13:15
 */
@RestController
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private JwtUtil jwtUtil;



    /*
     * @description: 处理根据博客的id获取该篇博客的评论列表
     * @params: [id]
     * @return: com.wdhcr.utils.ResponseResult
     * @author: wdhcr
     * @dateTime: 2020/4/12 13:17
     */
    @CrossOrigin
    @GetMapping("getListByBlogId/{id}")
    public ResponseResult getListByBlogId(@PathVariable Long id) throws Exception {
        List<Comment> comments = null;
        try {
            comments = commentService.findCommentListById(id);
        }catch (Exception e){
            throw new Exception("获取失败！");
        }
        return new ResponseResult(ResultCode.SUCCESS.getCode(),"获取成功!",comments);
    }

    /*
     * @description: 处理用户发表评论的方法
     * @params: [comment]
     * @return: com.wdhcr.utils.ResponseResult
     * @author: wdhcr
     * @dateTime: 2020/4/12 13:18
     */
    @CrossOrigin
    @PostMapping("saveComment")
    public ResponseResult saveComment(@RequestBody Comment comment) throws Exception {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("Authorization");
        if (token == null){
            return new ResponseResult(ResultCode.FAIL.getCode(),"获取失败！请重试！！",null);
        }
        Claims claims = jwtUtil.parseToken(token);
        String id = claims.getId();
        String openid = claims.getSubject();
        try {
            commentService.saveComment(comment,openid);
        }catch (Exception e){
//            e.printStackTrace();
            throw new Exception("评论失败！请重新登录");
        }
        return new ResponseResult(ResultCode.SUCCESS.getCode(),"评论成功!",null);
    }
}
